<template>
  <div class="container">
    <h2 class="homeTitle">用户统计</h2>
    <!-- 添加 v-if 来防止在数据加载完成前渲染空的图表容器 -->
    <div class="charBox" v-if="props.userdata && props.userdata.dateList">
      <!-- 关键修改：使用 ref="chartRef" 来代替 id -->
      <div ref="chartRef" style="width: 100%; height: 320px"></div>
      <ul class="orderListLine user">
        <li class="one"><span></span>用户总量（个）</li>
        <li class="three"><span></span>新增用户（个）</li>
      </ul>
    </div>
    <!-- 添加一个加载中或空状态的占位符 -->
    <div v-else class="charBox-placeholder">
      数据加载中...
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';
import type { PropType } from 'vue';
import * as echarts from 'echarts';

// --- 1. 定义 Props ---
const props = defineProps({
  userdata: {
    type: Object as PropType<any>,
    default: () => ({})
  }
});

// --- 2. ECharts 初始化与生命周期管理 ---
const chartRef = ref<HTMLElement | null>(null);
let myChart: echarts.ECharts | null = null;

const initChart = () => {
  // 确保 DOM 元素存在且数据有效
  if (chartRef.value && props.userdata && props.userdata.dateList) {
    myChart = myChart || echarts.init(chartRef.value);

    const option: echarts.EChartsOption = {
      tooltip: {
        trigger: 'axis',
        backgroundColor: '#fff',
        borderRadius: 2,
        textStyle: { color: '#333', fontSize: 12, fontWeight: 300 },
      },
      grid: {
        top: '5%',
        left: '20',
        right: '50',
        bottom: '12%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        axisLabel: { color: '#666', fontSize: 12 },
        axisLine: { lineStyle: { color: '#E5E4E4', width: 1 } },
        data: props.userdata.dateList,
      },
      yAxis: [{
        type: 'value',
        min: 0,
        axisLabel: { color: '#666', fontSize: 12 },
      }],
      series: [
        {
          name: '用户总量',
          type: 'line',
          smooth: false,
          showSymbol: false,
          itemStyle: {
            color: '#409EFF',
            lineStyle: { color: '#409EFF' },
          },
          emphasis: {
            focus: 'series',
            itemStyle: {
              color: '#fff',
              borderWidth: 5,
              borderColor: '#409EFF',
            },
          },
          data: props.userdata.totalUserList,
        },
        {
          name: '新增用户',
          type: 'line',
          smooth: false,
          showSymbol: false,
          itemStyle: {
            color: '#FD7F7F',
            lineStyle: { color: '#FD7F7F' },
          },
          emphasis: {
            focus: 'series',
            itemStyle: {
              color: '#fff',
              borderWidth: 5,
              borderColor: '#FD7F7F',
            },
          },
          data: props.userdata.newUserList,
        },
      ],
    };
    myChart.setOption(option);
  }
};

const resizeChart = () => {
  myChart?.resize();
};

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  myChart?.dispose();
});

// --- 3. 监听 Props 变化并更新图表 ---
watch(() => props.userdata, (newData) => {
  if (newData) {
    initChart();
  }
}, {
  deep: true,
});

</script>

<style lang="scss" scoped>
// 引入你的全局变量文件，以便使用颜色等
@import "@/styles/_variables.scss";

// 卡片式布局
.container {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  // 给一个最小高度，避免在加载时页面抖动
  min-height: 420px;
}

// 标题样式
.homeTitle {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 20px 0;
}

// 图表下方的图例 (从你的旧代码迁移而来)
.orderListLine.user {
  list-style: none;
  padding: 0;
  margin: 10px 0 0 0;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30px;
  font-size: 12px;
  color: #606266;

  li {
    display: flex;
    align-items: center;

    span {
      display: inline-block;
      width: 12px; // 图例标记宽度
      height: 4px; // 图例标记高度 (矩形)
      margin-right: 8px;
    }

    &.one span {
      background-color: #409EFF; // 对应“用户总量”的颜色
    }
    &.three span {
      background-color: #FD7F7F; // 对应“新增用户”的颜色
    }
  }
}

// 加载占位符样式
.charBox-placeholder {
  text-align: center;
  padding: 40px;
  color: #909399;
  height: 320px; /* 与图表高度保持一致 */
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
